<?php
/*
 * @Description:
 * @Author: 橘子味的心
 * @Date: 2020-11-20 22:26:32
 * @LastEditTime: 2021-01-13 20:55:35
 * @LastEditors: 橘子味的心
 * @Reference:
 */

namespace x_mier;

use think\facade\Db;

class Config
{
    /**
     * 获取数据库中的配置列表
     * @return array 配置数组
     */
    public function lists()
    {
        $map = array('state' => 1);
        $data = Db::name('system_config')->where($map)->field('type,name,value,extra')->select();
        $config = array();
        if ($data) {
            foreach ($data as $value) {
                $val = $value['value'];
                if ($value['type'] == 3) {
                    if (!empty($val)) {
                        $val = json_decode($val, true);
                    }
                } else if ($value['type'] == 4) {
                    if (isset($val)) {
                        $config[$value['name'] . '_extra'] = $this->extra($value['extra']);
                    }
                }
                $config[$value['name']] = $val;
            }
        }
        cache('config_data', $config);
        return $config;
    }
    private function extra($value)
    {
        $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
        if (strpos($value, ':')) {
            $value = array();
            foreach ($array as $val) {
                list($k, $v) = explode(':', $val);
                $value[$k] = $v;
            }
        } else {
            $value = $array;
        }
        return $value;
    }
    //附件
    public function attachment()
    {
        $file_data = \think\facade\Db::name('system_attachment')->field('file_id,storage,url')->select();
        $attachment = [];
        foreach ($file_data as $v) {
            $attachment[$v['file_id']] = [
                'storage' => $v['storage'],
                'url' => $v['url'],
            ];
        }
        cache('attachment', $attachment);
        return $attachment;
    }
    public function writelog($description, $status, $type = 0, $uid = '', $username = '', $types = '')
    {
        $id = $uid ? $uid : session('auth_user.id');
        $name = $username ?: session('auth_user.user_name');
        $ip = request()->ip();
        $ipaddr = get_ip_area($ip); //根据ip地址获取地域信息
        /****************************日志存入数据库*******************************/
        if ($types == '') {
            $data['auth_user_id'] = $id;
            $data['auth_user_name'] = $name;
            $data['describe'] = $description;
            $data['state'] = $status;
            $data['ip'] = $ip;
            $data['type'] = $type; //类型 0:操作日志 1:登录日志
            $data['create_time'] = time();
            $data['ipaddr'] = $ipaddr;
            $logId = \think\facade\Db::name('system_log')->insertGetId($data);
        } else {
            $logId = '空';
        }
        /****************************日志存入数据库*******************************/

        /****************************日志存入文件*******************************/
        if (config_group('log_std')) {
            $dir = 'log/' . date('Ymd', time());
            if (!is_dir($dir)) {
                if (!mkdir($dir, 0777, true)) {
                    return false;
                }
            }
            $file = 'log/' . date('Ymd', time()) . '/' . date('Ymd', time()) . '.txt';
            if (!is_file($file)) {
                $word = fopen($file, "a+");
                fwrite($word, "\r\n" . '+-------------+--------------+--------------+----------------------------------------------------------+----------------------+-------------------+-----------------+-----------------------+');
                fwrite($word, "\r\n" . '|             |              |              |                                                          |                      |                   |                 |                       |');
                fwrite($word, "\r\n" . '|     ID      |    用户ID    |   操作用户    |                     描述                                 |        操作IP         |        地址       |      状态        |        操作时间       |');
                fwrite($word, "\r\n" . '|             |              |              |                                                          |                      |                   |                 |                       |');
                fwrite($word, "\r\n" . '+-------------+--------------+--------------+----------------------------------------------------------+----------------------+-------------------+-----------------+-----------------------+');
                fclose($word);
            }
            $create_time = date('Y-m-d H:i:s', time());
            if ($status == 6) {
                $sta = '成功';
            } else {
                $sta = '失败';
            }
            file_put_contents($file, "\r\n " . $logId . ' +----------+ ' . $uid . ' +----------+ ' . $username . ' +----------+ ' . $description . ' +----------+ ' . $ip . ' +----------+ ' . $ipaddr . ' +----------+ ' . $sta . ' +----------+ ' . $create_time, FILE_APPEND);
            file_put_contents($file, "\r\n" . '+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+', FILE_APPEND);
        }
        /****************************日志存入文件*******************************/
    }
    /**
     * CURL发送Request请求,含POST和REQUEST
     * @param string $url     请求的链接
     * @param mixed  $params  传递的参数
     * @param string $method  请求的方法
     * @param mixed  $options CURL的参数
     * @return array
     */
    public function send_request($url, $data = [], $method = 'POST', $header = [], $header_null = false, $data_re = false)
    {
        $method = strtoupper($method);
        $protocol = substr($url, 0, 5);
        $header1 = [
            'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36',
            'Content-Type: application/json; charset=utf-8',
        ];
        if (empty($header)) {
            if (!$header_null) {
                $header = $header1;
            }
        } else {
            if (!$header_null) {
                $header = array_merge($header, $header1);
            }
        }
        //1. 初始化
        $ch = curl_init();
        //2.设置参数
        if (!empty($data)) {
            if (!empty($header) && $header_null == false) {
                $header = array_merge($header, ['Content-Length: ' . strlen(json_encode($data))]);
            }
            if ('POST' != $method) {
                $query = http_build_query($data);
                $url = $url . '?' . $query;
            }
        }
        if ('POST' == $method) {
            curl_setopt($ch, CURLOPT_POST, true);
            if (!empty($data)) {
                if (!$data_re) {
                    $data = json_encode($data);
                }
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            }
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //只获取页面内容,但不输出 return transfer
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        if ('https' == $protocol) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //忽略header头信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        //3.调用接口
        $ret = curl_exec($ch);
        $err = curl_error($ch);
        if (false === $ret || !empty($err)) {
            $errno = curl_errno($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            return [
                'ret' => false,
                'errno' => $errno,
                'msg' => $err,
                'info' => $info,
            ];
        }
        curl_close($ch);
        return [
            'ret' => true,
            'msg' => $ret,
        ];
    }
}
